/* This example program is in the public domain */

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "mgrx.h"

#define MAX_FONTLIST 300
#define MAX_FONTLOADED 20
#define DIR_FILE "lfpfonts.dir"

static char *lfont[MAX_FONTLIST];
static int nlfont;

static GrFont *grf[MAX_FONTLOADED];
static int grfp[MAX_FONTLOADED];
static int ngrf;

int loadfont(int n, int clear)
{
    if (clear) ngrf = 0;

    if (ngrf >= MAX_FONTLOADED) return -1;
    grf[ngrf] = GrLoadFont(lfont[n]);
    grfp[ngrf] = n;
    if (grf[ngrf] == NULL) return -1;
    ngrf++;

    return 0;
}

void unloadfonts(void)
{
    int i;

    for (i=0; i<ngrf; i++) {
        GrUnloadFont(grf[i]);
    }
}

int loadfontlist(char *file)
{
    FILE *f;
    char s[251];
    char *p;

    nlfont = 0;
    f = fopen(file, "rt");
    if (f == NULL) return -1;

    while (fgets(s, 250, f)) {
        p = strchr(s, ':');
        if (p && nlfont < MAX_FONTLIST) {
            *p = '\0';
            lfont[nlfont++] = strdup(s);
        }
    }
    return 0;
}

void printline(char *s, int x, int *y, int h, GrTextOption *grt)
{
    GrDrawString(s, strlen(s), x, *y, grt);
    *y += h;
}

void showeveryfont(void)
{
    GrTextOption grt;
    int k, i, x, y, h;
    char message[81];
    GrEvent ev;

    grt.txo_fgcolor.v = GrBlack();
    grt.txo_bgcolor.v = GrWhite();
    grt.txo_direct = GR_TEXT_RIGHT;
    grt.txo_xalign = GR_ALIGN_LEFT;
    grt.txo_yalign = GR_ALIGN_TOP;
    grt.txo_chrtype = GR_BYTE_TEXT;

    for (k=0; k<nlfont; k++) {
        if (loadfont(k,1) == 0) {
            x = 2;
            y = 2;
            GrClearScreen(GrWhite());
            h = GrFontCharHeight(grf[0], 'M') + 4;
            grt.txo_font = grf[0];

            sprintf(message, "%s: Hello, GRX world!",lfont[grfp[0]]);
            printline(message, x, &y, h, &grt);
            y += h;

            printline("abcdefghijklm", x, &y, h, &grt);
            printline("nopqrstuvwxyz", x, &y, h, &grt);
            y += h;

            printline("ABCDEFGHIJKLM", x, &y, h, &grt);
            printline("NOPQRSTUVWXYZ", x, &y, h, &grt);
            y += h;

            printline("0123456789 [\\]^_`{|}~", x, &y, h, &grt);
            printline("!\"#$%&'()*+,-./:;<=>?@", x, &y, h, &grt);
            printline("�� ����", x, &y, h, &grt);
            y += h;

            GrEventWaitKeyOrClick(&ev);
            unloadfonts();
        }
    }
}

int main()
{
    GrSetMode( GR_default_graphics );
    GrEventInit();

    if (loadfontlist(DIR_FILE) == 0) {
        showeveryfont();
    }

    GrEventUnInit();
    return 0;
}

